package com.xxd.gulimail.product.service.impl;

import com.xxd.gulimail.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxd.common.utils.PageUtils;
import com.xxd.common.utils.Query;

import com.xxd.gulimail.product.dao.CategoryDao;
import com.xxd.gulimail.product.entity.CategoryEntity;
import com.xxd.gulimail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private CategoryDao categoryDao;
    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @Description: 查出所有分类，组装成父子的树形结构
     * @Author: xuxd
     * @Date: 2022/9/30 12:11
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);//queryWrapper相当于查询条件，where,group by,order by,limit....
        //2.选出第一级菜单,层级为1；
        List<CategoryEntity> level1Menus = categoryEntityList.stream().filter(categoryEntity -> {//java8新的抽象称为流Stream
            return categoryEntity.getCatLevel() == 1;
        }).map(menu -> {//将一级菜单的子菜单设置进去
            menu.setChildren(getChildrens(menu, categoryEntityList));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List catIds) {
        //TODO:1.检查当前删除的菜单是否被别的地方引用
        //逻辑删除，mybatis-plus,配置mybatis-plus.logic的值，并配置实体类的字段（底层update）
        baseMapper.deleteBatchIds(catIds);
    }


    //递归查询子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> categoryEntityList) {
        List<CategoryEntity> children = categoryEntityList.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {//递归查询子菜单的子菜单。
            categoryEntity.setChildren(getChildrens(categoryEntity, categoryEntityList));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());//menu可能为null.
        }).collect(Collectors.toList());
        return children;
    }

    //根据id查询它的子菜单
    @Override
    public List<CategoryEntity> getAllChildrenById(Long catId) {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);//queryWrapper相当于查询条件，where,group by,order by,limit....
        CategoryEntity root = getById(catId);
        return getChildrens(root, categoryEntityList);
    }

    /**
     * @Description: 根据id查出分类详情【父、子】
     * @Author: xuxd
     * @Date: 2022/10/15 21:31
     */
    @Override
    public Long[] getcatelogPath(Long categoryId) {
        List<Long> list = new ArrayList<>();
        List paths = findPerantPath(categoryId,list);
        Collections.reverse(paths);
        return  list.toArray(new Long[0]);
    }

    /**
     * @Description: 级联更新所有关联的字段
     * @Author: xuxd
     * @Date: 2022/10/16 18:11
     */
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
        }
    }

    //根据categoryId递归查询父节点id,放入list容器中
    private List<Long> findPerantPath(Long categoryId, List<Long> list) {
        list.add(categoryId);
        if(this.getById(categoryId).getParentCid() !=0){
            findPerantPath(this.getById(categoryId).getParentCid(),list);
        }
        return list;
    }
}